package com.wuzf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import com.wuzf.dao.RoleDao;
import com.wuzf.entity.Role;
import com.wuzf.utils.JdbcTemplateUtils;

public class RoleDaoImpl implements RoleDao {
	
	private JdbcTemplate template = JdbcTemplateUtils.JdbcTemplate();

	public Role createRole(final Role role) {
		final String sql = "insert into sys_roles (role, description, available) values (?, ?, ?) ";
		GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
		template.update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement psm = con.prepareStatement(sql, new String[]{"id"});
				psm.setString(1, role.getRole());
				psm.setString(2, role.getDescription());
				psm.setBoolean(3, role.getAvailable());
				return psm;
			}
		}, keyHolder);
		role.setId(keyHolder.getKey().longValue());
		return role;
	}

	public void deleteRole(Long roleId) {
		// TODO Auto-generated method stub

	}

	public void correlationPermissions(Long roleId, Long... permissionIds) {
		if (permissionIds == null || permissionIds.length == 0) {
			return;
		}
		String sql = "insert into sys_roles_permissions (role_id, permission_id) values (?, ?)";
		System.out.println("插入角色权限表");
		for (Long permissionId : permissionIds) {
			if (!exists(roleId, permissionId)) {
				System.out.println("更新角色权限表内容" + permissionId + ":" + roleId);
				template.update(sql, roleId, permissionId);
			}
		}
	}
	
	public boolean exists(Long roleId, Long permissionId) {
		String sql = "select count(1) from sys_roles_permissions where role_id = ? and permission_id = ? ";
		return template.queryForObject(sql, Integer.class, roleId, permissionId) != 0;
	}

	public void uncorrelationPermissions(Long roleId, Long... permissionIds) {
		// TODO Auto-generated method stub

	}

}
